package org.javaboy.dynamic_datasource.ds;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

    YamlDynamicDataSourceProvider yamlDynamicDataSourceProvider;

    public DynamicDataSource(YamlDynamicDataSourceProvider yamlDynamicDataSourceProvider) {
        this.yamlDynamicDataSourceProvider = yamlDynamicDataSourceProvider;
        //设置所有的数据源
        Map<String, DataSource> sourceMap = yamlDynamicDataSourceProvider.loadAllDataSource();
        setTargetDataSources(new HashMap<>(sourceMap));
        //默认的数据源
        setDefaultTargetDataSource(sourceMap.get("master"));
    }

    /**
     * 这个方法是返回数据源的 key
     *
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSource();
    }
}
